import {useStore} from "@/stores";
import req, {createAxios} from "@/apis/axios/axios-req";

const ssoService: any = createAxios(import.meta.env.VITE_APP_SSO_URL);
const bsService: any = createAxios(import.meta.env.VITE_APP_BASE_API);

const handleParams = (params: any) => {
    const store = useStore();
    const cred = store.getCredential();

    if (!params.headers) {
        params.headers = {};
    }

    if (cred && cred.accessToken) {
        params.headers['access_token'] = cred.accessToken;
    }

    if (!params.headers['Content-Type']) {
        params.headers['Content-Type'] = 'application/json;charset=utf-8'
    }

    params.headers['client_id'] = import.meta.env.VITE_APP_CLIENT_ID;
    params.headers['client_secret'] = import.meta.env.VITE_APP_CLIENT_SECRET;
    params.headers['terminal_code'] = 'WEB';
    params.headers['platform'] = import.meta.env.VITE_APP_PLATFORM;

    return params;
}

export const doRequest = async (params: any, axiosReq: any) => {
    let result: any;
    try {
        const store = useStore();
        const cred = store.getCredential();

        if (!params.headers) {
            params.headers = {};
        }

        if (cred) {
            params.headers['access_token'] = cred.accessToken || '';
        }

        if (!params.headers['Content-Type']) {
            params.headers['Content-Type'] = 'application/json;charset=utf-8'
        }

        params.headers['client_id'] = import.meta.env.VITE_APP_CLIENT_ID;
        params.headers['client_secret'] = import.meta.env.VITE_APP_CLIENT_SECRET;
        params.headers['terminal_code'] = 'WEB';
        params.headers['platform'] = import.meta.env.VITE_APP_PLATFORM;

        console.log('--- request, 开始调用接口', params);
        result = await axiosReq(params);
        console.log('--- request, 调用接口返回', result);
        result = result.data;

        if (101000 == result.code) {
            window.location.href = window.location.origin;
        }
    } catch (e) {
        console.log('--- response, 调用接口异常', e);
        result = {
            code: 502,
            message: '网络异常,请稍后再试!',
        }
    }
    return result;
}

export const requestForm = async (params: any) => {
    let result: any;
    try {
        const reqParams: any = handleParams(params);
        console.log('--- request, 开始调用接口', reqParams);
        result = await axiosReq(reqParams);
        if (result) {
            result = result.data;
        }
        console.log('--- request, 调用接口返回', result);
    } catch (e) {
        console.log('--- response, 调用接口异常', e);
    }
    return result;
}

export const request = async (params: any) => {
    return await doRequest(params, req)
}

export const bsRequest = async (params: any) => {
    return await doRequest(params, bsService)
}

export const ssoRequest = async (params: any) => {
    return await doRequest(params, ssoService)
}
